<template>
  <div class="fullMain" style="max-height: calc(100% - 50px); overflow: scroll">
    <div style="position: fixed; width: 100%; z-index: 999">
      <x-header :left-options="{ backText: '', showBack: false }"
        >汇报情况统计</x-header
      >
    </div>
    <div style="height: 55px" />
    <!--插入验证提示框-->
    <div v-transfer-dom>
      <alert v-model="isShowAlert">{{ alertText }}</alert>
    </div>
    <div class="mainbBg">
      <div
        class="groupStatistic"
        v-for="(item, index) in allGroupList"
        :key="index"
      >
        <group class="groupList">
          <cell
            class="groupListCell"
            is-link
            :title="groupTitle(item.group.detail)"
            :class="chooseIndex === index ? 'choosed' : ''"
            @click.native="unfoldOrFold(item, index)"
          >
            <!-- <badge :text="item.finishedReportNum" class="groupListBadge"></badge> -->
          </cell>
        </group>
        <div class="statisticsContent" v-if="chooseIndex === index">
          <div class="studentList">
            <div
              class="studentItem"
              v-for="(item, index) in groupMembers"
              :key="index"
              @click="chooseUser(index, item.userId)"
              :style="{
                border: chooseUserIndex === index ? '1px solid gray' : '',
              }"
            >
              <img :src="item.avatar" alt class="manager_avatar" />
              <br />
              <span>{{ item.userName }}</span>
            </div>
          </div>

          <div class="reportDetail">
            <!-- <div class="notReport">
              <span class="contentTitle">未汇报成员</span>
              <div class="notReportList">
                <span
                  class="notReportListDetail"
                  v-for="(item_notReport,index_notReport) in notReportList"
                  :key="index_notReport"getUserLatestRepo
                >{{item_notReport}}</span>
              </div>
            </div>-->
            <div class="latestRepo">
              <div
                class="latestRepoDetail"
                v-for="(item, index) in groupMembers[chooseUserIndex]
                  .activities"
                :key="index"
              >
                <span class="type">{{ item.typeContent }}</span>
                <span class="time"
                  >{{ item.startTime }}--{{ item.endTime }}</span
                >
                <br />
                <span class="content">{{ item.content }}</span>
              </div>
            </div>
            <div class="chart">
              <span class="contentTitle">一周用时分布</span>
              <v-chart :data="data" class="timeDistribution">
                <v-scale x :options="xOptions" />
                <v-tooltip disabled />
                <v-pie class="pie" :radius="0.85" series-field="name" />
                <v-legend :options="legendOptions" />
              </v-chart>
            </div>
            <!-- <div class="chart">
              <canvas id="myChart" style="width: 100%"></canvas>
            </div> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { XHeader, Group, Cell, Badge } from "vux";
import {
  VChart,
  VLine,
  VArea,
  VTooltip,
  VLegend,
  VBar,
  VPie,
  VScale,
} from "vux";
import { mapState } from "Vuex";
import group from "api/group";
import report from "api/report";
import hashMap from "utilMethods/hashMap";
import F2 from "@antv/f2";
let map = new hashMap();
export default {
  name: "SituationStatistics",
  components: {
    XHeader,
    Group,
    Cell,
    Badge,
    VChart,
    VLine,
    VArea,
    VTooltip,
    VLegend,
    VBar,
    VPie,
    VScale,
  },
  data() {
    return {
      isShowAlert: false, // 是否显示验证提示框
      alertText: "",
      allGroupList: [],
      chooseIndex: 0,
      // notReportList: ["文攀", "何秀靖", "王知远"],
      groupMembers: [],
      chooseUserIndex: 0,
      chooseUserId: "",
      // 图标相关
      data: [{ name: "芳华", percent: 0.4, a: "1" }],
      legendOptions: {
        position: "top",
        itemFormatter(val) {
          let value = map.get(val);
          if (value !== null) {
            value = value.toFixed(2);
          }
          return val + " " + value + "h";
        },
      },
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  mounted() {
    // this.test();
    this.getReportedNumber();
  },
  methods: {
    test() {
      const map = {
        芳华: "40%",
        妖猫传: "20%",
        机器之血: "18%",
        心理罪: "15%",
        寻梦环游记: "5%",
        其他: "2%",
      };
      const data = [
        {
          name: "芳华",
          percent: 0.4,
          a: "1",
        },
        {
          name: "妖猫传",
          percent: 0.2,
          a: "1",
        },
        {
          name: "机器之血",
          percent: 0.18,
          a: "1",
        },
        {
          name: "心理罪",
          percent: 0.15,
          a: "1",
        },
        {
          name: "寻梦环游记",
          percent: 0.05,
          a: "1",
        },
        {
          name: "其他",
          percent: 0.02,
          a: "1",
        },
      ];
      const chart = new F2.Chart({
        id: "myChart",
        pixelRatio: window.devicePixelRatio,
      });
      chart.source(data, {
        percent: {
          formatter: function formatter(val) {
            return val * 100 + "%";
          },
        },
      });
      chart.legend({
        position: "right",
        itemFormatter: function itemFormatter(val) {
          return val + "  " + map[val];
        },
      });
      chart.tooltip(false);
      chart.coord("polar", {
        transposed: true,
        radius: 0.85,
      });
      chart.axis(false);
      chart
        .interval()
        .position("a*percent")
        .color("name", [
          "#1890FF",
          "#13C2C2",
          "#2FC25B",
          "#FACC14",
          "#F04864",
          "#8543E0",
        ])
        .adjust("stack")
        .style({
          lineWidth: 1,
          stroke: "#fff",
          lineJoin: "round",
          lineCap: "round",
        })
        .animate({
          appear: {
            duration: 1200,
            easing: "bounceOut",
          },
        });

      chart.render();
    },
    //《《基础功能
    // 验证提示框
    showAlert(alertText) {
      this.isShowAlert = true;
      this.alertText = alertText;
    },
    closeTip() {
      this.isShowAlert = false;
      this.alertText = "";
    },
    back() {
      this.$router.go(-1);
    },

    //《《页面功能
    async getLatestReportList(groupId) {
      const result = await report.getLatestRepoList(groupId);
      if (result.code === 0) {
        this.showAlert("群成员获取失败，请稍后再试");
      } else if (result.code === 1) {
        this.groupMembers = result.data;
        this.chooseUser(0, this.groupMembers[0].userId);
      }
    },
    unfoldOrFold(item, index) {
      if (index === this.chooseIndex) {
        this.chooseIndex = null;
      } else {
        this.chooseIndex = index;
        this.getLatestReportList(item.group.groupId);
      }
    },
    groupTitle(group) {
      return group.groupName;
    },
    async getReportedNumber() {
      const result = await group.getGroupStatistics();
      if (result.code === 0) {
        this.showAlert("查询失败，请重试。");
      } else {
        this.allGroupList = result.data;
        this.getLatestReportList(this.allGroupList[0].group.groupId);
      }
    },
    chooseUser(index, userId) {
      this.chooseUserIndex = index;
      this.chooseUserId = userId;
      this.getPieData();
    },
    async getPieData() {
      let timePeriod = this.getOneWeek();
      const result = await report.getReportsByUserId({
        userId: this.chooseUserId,
        start: timePeriod.weekAgo,
        end: timePeriod.now,
      });
      let reports = result.data;
      let typeContent = [];
      let totalTime = 0;
      map = new hashMap();
      this.data.splice(0);
      reports.forEach((element) => {
        element.activities.forEach((element_in) => {
          let period = this.getTimePeriod(
            element_in.startTime,
            element_in.endTime
          );
          totalTime += period;
          if (map.get(element_in.typeContent) === null) {
            typeContent.push(element_in.typeContent);
          }
          map.put(
            element_in.typeContent,
            map.get(element_in.typeContent) + period
          );
        });
      });
      typeContent.forEach((element) => {
        this.data.push({
          name: element,
          percent: map.get(element) / totalTime,
          a: "1",
        });
      });
    },
    getTimePeriod(startTime, endTime) {
      //10:00:00,11:45:00
      let startHour = +startTime.substring(0, 2);
      let startMinute = +startTime.substring(3, 5);
      let endHour = +endTime.substring(0, 2);
      let endMinute = +endTime.substring(3, 5);
      let hour = endHour - startHour;
      let minute = endMinute - startMinute;
      let period = hour + minute / 60;
      return +period.toFixed(2);
    },
    // 获取今天的日期和一周前的日期
    getOneWeek() {
      let now = new Date();
      let nowMonth = now.getMonth() + 1;
      let nowDay = now.getDate();
      if (nowMonth < 10) nowMonth = "0" + nowMonth;
      if (nowDay < 10) nowDay = "0" + nowDay;
      let nowDate = now.getFullYear() + "-" + nowMonth + "-" + nowDay;

      let weekAgo = new Date(now.getTime() - 7 * 24 * 3600 * 1000);
      let weekAgoMonth = weekAgo.getMonth() + 1;
      let weekAgoDay = weekAgo.getDate();
      if (weekAgoMonth < 10) weekAgoMonth = "0" + weekAgoMonth;
      if (weekAgoDay < 10) weekAgoDay = "0" + weekAgoDay;
      let weekAgoDate =
        weekAgo.getFullYear() + "-" + weekAgoMonth + "-" + weekAgoDay;
      return { now: nowDate, weekAgo: weekAgoDate };
    },
  },
};
</script>
<style lang="less">
.choosed {
  border: 1px solid rgb(191, 191, 191);
  border-radius: 5px;
  box-shadow: 0px 1px 5px rgb(191, 191, 191);
}

.groupStatistic {
  .groupList {
    margin-top: -15px;
    .groupListCell {
      padding: 0 5px;
    }
  }
  .statisticsContent {
    height: 500px;
    overflow: auto;
    display: flex;
    .studentList {
      min-width: 52px;
      height: 100%;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      .studentItem {
        box-sizing: border-box;
        width: 51px;
        height: 72px;
        border-bottom: 1px solid white;
        background-color: #ddd;
        padding: 2px 5px 2px 0;
        margin-left: 0;
        img {
          width: 47px;
          height: 47px;
          border-radius: 50%;
          border: 1px solid #ddd;
        }
        span {
          width: 47px;
          display: inline-block;
          font-size: 11px;
          color: gray;
          overflow: hidden;
          text-align: center;
        }
      }
    }
    .reportDetail {
      margin: 5px;
      display: flex;
      flex-direction: column;
      width: 99%;
      height: 98%;
      overflow: hidden;
      .notReport {
        .notReportList {
          margin: 4px 0;
          padding: 10px 5px 5px 5px;
          .notReportListDetail {
            border: 1px solid gray;
            border-radius: 2px;
            padding: 2px 5px;
            margin-right: 5px;
          }
        }
      }
      .contentTitle {
        background-color: rgb(191, 191, 191);
        border-radius: 2px;
        font-family: Helvetica, Arial, sans-serif;
        font-size: 10px;
        font-weight: bolder;
        padding: 5px;
      }
      .latestRepo {
        border: 1px solid rgb(191, 191, 191);
        border-radius: 5px;
        box-shadow: 0px 1px 5px rgb(191, 191, 191);
        background-color: white;
        padding: 5px;
        font-family: "微软雅黑";
        font-size: small;
        margin-bottom: 5px;
        .date {
          color: rgb(191, 191, 191);
          float: right;
        }
        .latestRepoDetail {
          margin-bottom: 10px;
          .type {
            font-family: "微软雅黑 Light";
            font-weight: bold;
            color: #656565;
          }
          .time {
            color: rgb(191, 191, 191);
          }
          .content {
            color: grey;
            overflow-wrap: break-word;
            white-space: normal;
          }
        }
        .plan {
          color: grey;
          font-size: small;
          letter-spacing: 0.5px;
          overflow-wrap: break-word;
          white-space: normal;
        }
      }
      .chart {
        border: 1px solid red;
        .timeDistribution {
          border: 1px solid rgb(191, 191, 191);
          border-radius: 5px;
          box-shadow: 0px 1px 5px rgb(191, 191, 191);
          margin-top: 4px;
          .pie {
          }
        }
      }
    }
  }
}
</style>
